package com.changjiang.luban.admin;

import com.alibaba.fastjson.JSON;
import com.changjiang.luban.config.annotation.AuthorizationToken;
import com.changjiang.luban.config.annotation.CurrentUser;
import com.changjiang.luban.config.exception.FileUploadException;
import com.changjiang.luban.dao.domain.sys.SysPermission;
import com.changjiang.luban.dao.domain.sys.SysRole;
import com.changjiang.luban.dao.domain.sys.SysUser;
import com.changjiang.luban.dao.domain.sys.SysLog;
import com.changjiang.luban.model.AuthorizationUser;
import com.changjiang.luban.service.sys.LogServiceI;
import com.changjiang.luban.service.sys.SysRoleServiceI;
import com.changjiang.luban.service.sys.SysUserServiceI;
import com.changjiang.luban.utils.DateUtils;
import com.changjiang.luban.utils.data.Page;
import com.changjiang.luban.utils.data.Tree;
import com.changjiang.luban.utils.encryption.MD5Utils;
import com.changjiang.luban.utils.result.ApiResult;
import com.changjiang.luban.utils.result.ApiResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * SysController
 * Description:
 *
 * @author nichangjiang@vip.qq.com
 * @version v0.1
 * @date 2018/6/9 - 22:04
 */
@SuppressWarnings("ALL")
@Controller
@RequestMapping("/admin/sys")
public class SysController {

    @Autowired
    private SysUserServiceI sysUserServiceI;

    @Autowired
    private SysRoleServiceI roleServiceI;

    @Autowired
    private LogServiceI logServiceI;

    /**
     * Api数据返回封装对象
     */
    private ApiResult apiResult = ApiResult.success();

    /**
     * 管理员信息页面
     * @return
     */
    @GetMapping("/user")
    public String userIndex() {
        return "/sys/sys_users";
    }

    /**
     * 添加管理员信息页面
     * @param request
     * @param session
     * @return
     */
    @GetMapping("/user/add")
    public String userAdd(HttpServletRequest request, HttpSession session) {
        List<SysRole> roles = roleServiceI.findByState(1);
        request.setAttribute("roles", roles);
        return "/sys/sys_user_add";
    }

    @GetMapping("/user/info/{id}")
    public String userInfo(@PathVariable Long id, HttpServletRequest request, HttpSession session) {
        SysUser user = sysUserServiceI.findById(id);
        request.setAttribute("user", user);
        return "/sys/sys_user_info";
    }

    /**
     * 分页查询管理员信息页面
     * @param search
     * @param index
     * @return
     */
    @PostMapping("/users")
    @ResponseBody
    public ApiResult list(String search, Integer index) {
        Page<SysUser> page = new Page<>();
        page.setIndex(index);
        page = sysUserServiceI.pageByName(search, page);
        page.getPageBar();
        return ApiResult.success(page);
    }


    /**
     * 添加用户信息
     * @param user   用户实体
     * @param bindingResult
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/save",name = "添加新用户")
    @ResponseBody
    public ApiResult saveUser(@Valid SysUser user,Long roleId, BindingResult bindingResult) throws FileUploadException {
        user.setInsertTime(DateUtils.getCurrentSystemDate(DateUtils.DATE_FORMAT_COMPLETE));
        user.setPassWord(MD5Utils.encodeMd5("123456"));
        apiResult = ApiResult.success(sysUserServiceI.saveSysUser(user, roleId));
        apiResult.setCallback("/admin/sys/user");
        return apiResult;
    }

    @PostMapping(value = "/user/delete",name = "删除用户")
    @ResponseBody
    public ApiResult deleteUser(Long id){
        apiResult = ApiResult.success(sysUserServiceI.delete(id));
        apiResult.setCallback("/admin/sys/user");
        return apiResult;
    }

    /**
     * 初始化管理密码
     * @param id  用户编号
     * @return
     */
    @PostMapping("/initialize")
    @ResponseBody
    public ApiResult initialize (Long id){
        SysUser user = sysUserServiceI.findById(id);
        user.setPassWord(MD5Utils.encodeMd5("123456"));
        boolean bool = sysUserServiceI.updateSysUser(user);
        if (!bool){
            apiResult = ApiResult.failure(ApiResultCode.OPERATION_FAILED);
        }
        apiResult.setCallback("/admin/sys/user");
        return apiResult;
    }

    /**
     * 权限菜单页面
     * @return
     */
    @GetMapping("/permission")
    public String permission() {
        return "/sys/sys_permission";
    }


    /**
     * 分页查询权限菜单信息
     * @param index  页码
     * @return
     */
    @PostMapping("/permissions")
    @ResponseBody
    public ApiResult permissionList(Integer index) {
        Page<SysPermission> page = new Page<>();
        page.setIndex(index);
        page = sysUserServiceI.page(page);
        page.getPageBar();
        return ApiResult.success(page);
    }

    /**
     * 角色信息页面
     * @return
     */
    @GetMapping("/role")
    public String role() {
        return "/sys/sys_role";
    }

    /**
     * 添加角色信息页面
     * @return
     */
    @GetMapping("/role/add")
    public String roleAdd(HttpServletRequest request) {
        List<Tree> tree = sysUserServiceI.tree();
        request.setAttribute("treeView",tree);
        return "/sys/sys_role_add";
    }

    /**
     * 分页查询角色信息
     * @param search  查询参数
     * @param index   页码
     * @return
     */
    @PostMapping("/roles")
    @ResponseBody
    public ApiResult roleList(String search,Integer index)throws Exception {
        Page<SysRole> page = new Page<>();
        page.setIndex(index);
        page = roleServiceI.pageByName(search,page);
        page.getPageBar();
        return ApiResult.success(page);
    }

    /**
     * 添加角色信息
     * @param role   角色实体
     * @param bindingResult
     * @return
     * @throws IOException
     */
    @PostMapping("/saveRoles")
    @ResponseBody
    public ApiResult saveRoles(@Valid SysRole role,String tree,BindingResult bindingResult) throws FileUploadException {
        List<String> treeList = Arrays.asList(tree.split(","));
        if(treeList.size()>0){
            Set<SysPermission> permissionList = sysUserServiceI.findAll(treeList);
            role.setPermissions((Set<SysPermission>) permissionList);
        }
        role.setIsDefault(0);
        boolean bool= roleServiceI.saveSysRole(role);
        if(!bool){
            apiResult = ApiResult.failure(ApiResultCode.OPERATION_FAILED);
        }
        apiResult.setCallback("/admin/sys/role");
        return apiResult;
    }

    /**
     * 权限菜单页面
     * @return
     */
    @GetMapping("/role/{id}")
    @AuthorizationToken
    public String roleInfo(@PathVariable Long id, @CurrentUser AuthorizationUser token,HttpServletRequest request) {
        List<Tree> tree = sysUserServiceI.tree();
        List<Tree> userTree = sysUserServiceI.treeRole(id);
        tree = Tree.treeSign(tree,userTree);
        SysRole role = roleServiceI.findInfo(id);
        request.setAttribute("treeView",tree);
        request.setAttribute("role",role);
        System.out.println(JSON.toJSONString(tree));
        return "/sys/sys_role_info";
    }

    /**
     * 修改角色信息
     * @param role
     * @param tree
     * @param bindingResult
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/role/update",name = "修改角色信息")
    @ResponseBody
    public ApiResult updateRole(@Valid SysRole role,String tree,BindingResult bindingResult,@CurrentUser AuthorizationUser user) throws FileUploadException {
        List<String> treeList = Arrays.asList(tree.split(","));
        if(treeList.size()>0){
            Set<SysPermission> permissionList = sysUserServiceI.findAll(treeList);
            role.setPermissions((Set<SysPermission>) permissionList);
        }
        List<SysUser> users = sysUserServiceI.findAll(role.getId());
        if(users.size()>0){
            Set<SysUser> usersList = new HashSet<SysUser>();
            for (SysUser user1:users) {
                usersList.add(user1);
            }
            role.setUsers(usersList);
        }
        role.setIsDefault(0);
        boolean bool = roleServiceI.updateRole(role);
        if (!bool) {
            apiResult = ApiResult.failure(ApiResultCode.OPERATION_FAILED);
        }
        apiResult.setCallback("/admin/sys/role");
        return apiResult;
    }


        /**
         * 修改角色状态
         * @param id   角色编号
         * @param state 状态
         * @return
         */
    @PostMapping("/updateRole")
    @ResponseBody
    public ApiResult updateRole(Long id, Integer state){
        boolean bool= roleServiceI.updateState(id, state);
        if(!bool){
            apiResult = ApiResult.failure(ApiResultCode.OPERATION_FAILED);
        }
        apiResult.setCallback("/admin/sys/role");
        return apiResult;
    }

    /**
     * 日志信息页面
     * @return
     */
    @GetMapping("/log")
    public String log (){
        return "/sys/sys_log";
    }

    /**
     * 分页查询日志信息
     * @param index
     * @return
     */
    @PostMapping("/logList")
    @ResponseBody
    public ApiResult logList(Integer index){
        Page<SysLog> page = new Page<>();
        page.setIndex(index);
        page = logServiceI.pageList(page);
        page.getPageBar();
        return ApiResult.success(page);
    }

    @PostMapping("/log/delete")
    @ResponseBody
    public ApiResult deleteLog(Integer type){
        apiResult = ApiResult.success(logServiceI.delete(type));
        apiResult.setCallback("/admin/sys/log");
        return apiResult;
    }

}
